package com.example.shop_2211.fragment

import android.app.Activity
import android.os.Bundle
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.ToastUtils
import com.example.base.entity.OrderDetail
import com.example.base.entity.PreOrderEntityParam
import com.example.base.mvvm.BaseFragment
import com.example.shop_2211.R
import com.example.shop_2211.adapter.CarAdapter
import com.example.shop_2211.databinding.FragmentCartBinding
import com.example.shop_2211.fgViewModel.CartViewModel
import com.umeng.socialize.ShareAction
import com.umeng.socialize.UMShareListener
import com.umeng.socialize.bean.SHARE_MEDIA

class CartFragment : BaseFragment<FragmentCartBinding,CartViewModel>() {
    lateinit var carAdapter: CarAdapter
    override fun initView() {
        carAdapter = CarAdapter()
        binding.rvCar.adapter = carAdapter
        binding.rvCar.layoutManager = LinearLayoutManager(context)
        //请求购物车数据
        viewModel.getCar("true","10","1")
        //点击全选、+ —图标
        carAdapter.addChildClickViewIds(R.id.car_cb,R.id.car_add,R.id.car_sub)
        carAdapter.setOnItemChildClickListener { adapter, view, position ->
            when(view.id){
                R.id.car_cb->{
                    carAdapter.data[position].isChecked = !carAdapter.data[position].isChecked
                }
                R.id.car_add->{
                    carAdapter.data[position].cartNum++
                    (carAdapter.getViewByPosition(position,R.id.car_num) as TextView).text = "${carAdapter.data[position].cartNum}"
                    viewModel.updateCar(carAdapter.data[position].id,carAdapter.data[position].cartNum)
                }
                R.id.car_sub->{
                    if(carAdapter.data[position].cartNum==1){
                        val ids = arrayOf(carAdapter.data[position].id)
                        viewModel.deleteCar(ids)
                        carAdapter.data.removeAt(position)
                        //局部刷新
                        carAdapter.notifyItemRemoved(position)
                        //carAdapter.notifyDataSetChanged()
                    }else{
                        carAdapter.data[position].cartNum--
                        (carAdapter.getViewByPosition(position,R.id.car_num) as TextView).text = "${carAdapter.data[position].cartNum}"
                        viewModel.updateCar(carAdapter.data[position].id,carAdapter.data[position].cartNum)
                    }
                }
            }
            //计算金额
            checkMoney()
            //计算是否全选了
            checkCb()
        }
            //底部全选按钮的点击事件
        binding.cb.setOnCheckedChangeListener { buttonView, isChecked ->
            binding.cb.setOnClickListener { //只有点击时，上方的rv数据发生变化
                carAdapter.data.forEach {
                    it.isChecked = isChecked
                }
                carAdapter.notifyDataSetChanged()
                checkMoney()//再次结算金额
            }
        }
        //点击结算，生成预下单，并跳转到支付页面
        binding.pay.setOnClickListener {
            //判断是否有商品被选中
            val list  = mutableListOf<Boolean>()
            carAdapter.data.forEach {
                list.add(it.isChecked)
            }
            if(true in list){
                //生成预订单数据
                val preOrderEntityParam = PreOrderEntityParam()
                //给预下单数据添加值
                preOrderEntityParam.preOrderType = "shoppingCart"//修改添加方式
                val details = mutableListOf<OrderDetail>()
                carAdapter.data.forEach {
                    if(it.isChecked){
                        val orderDetail = OrderDetail()
                        orderDetail.shoppingCartId = it.id//获取购物车选中数据的id
                        details.add(orderDetail)//将选中的商品添加到预下单数据中
                    }
                }
                preOrderEntityParam.orderDetails = details
                Log.d("sss", "initView: $preOrderEntityParam")
                viewModel.preOrder(preOrderEntityParam)
            }else{
                ToastUtils.showLong("请选择至少一个商品去结算")
            }
        }
    }

    private fun checkCb() {
        val list = mutableListOf<Boolean>()
        carAdapter.data.forEach {
            list.add(it.isChecked)
        }
     /*   if(false in list){
            binding.cb.isChecked = false
        }else{
            binding.cb.isChecked = true
        }*/
        binding.cb.isChecked = false !in list
    }

    private fun checkMoney() {
        var amount = 0f
        carAdapter.data.forEach {
            if(it.isChecked){
                amount+=it.price.toFloat()*it.cartNum
            }
        }
        binding.money.text = "合计：￥$amount"
    }

    override fun initData() {
        viewModel.getSuccess.observe(this){
            if(it.code==200){
                carAdapter.data.clear()
                carAdapter.data.addAll(it.data.list)
                carAdapter.notifyDataSetChanged()
            }else{
                ToastUtils.showLong(it.message)
            }
        }
        viewModel.updateSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.updateFail.observe(this){
            ToastUtils.showLong(it)
        }
        viewModel.deleteSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }
        viewModel.preOrderSuccess.observe(this){
            ToastUtils.showLong(it.message)
            Log.d("sss", "initData:${it}")
            if(it.code==200){
                ARouter.getInstance().build("/app/OrderActivity").withString("preOrderNo",it.data.preOrderNo).navigation()
            }
        }

    }

    override fun getViewModel(): Class<CartViewModel>  = CartViewModel::class.java

    override fun getLayout(): Int  = R.layout.fragment_cart

}